<?php
class TradeCertificatePage extends MemberPage implements i18nEntityProvider {
	private static $singular_name = "Trade Certificate Page";
    private static $plural_name = "Trade Certificate Pages";
	
    private static $default_parent = 'TradingPage';

    private static $db = array();
	
	function provideI18nEntities() {
		$entities = parent::provideI18nEntities();
		foreach(TradeSetting::get() as $trade_setting){
			$entities[sprintf('%s.%s', 'TradeCertificatePage', strtoupper(str_replace(' ', '_', preg_replace("/[^ \w]+/", "", $trade_setting->Title))))] = array(strtoupper($trade_setting->Title));
		}
		return $entities;
	}
}

class TradeCertificatePage_Controller extends MemberPage_Controller {

    /**
     * An array of actions that can be accessed via a request. Each array element
     * should be an action name, and the
     * permissions or conditions required to allow the user to access it.
     *
     * <code>
     * array (
     *     'action', // anyone can access this action
     *     'action' => true, // same as above
     *     'action' => 'ADMIN', // you must have ADMIN permissions to access this
     * action
     *     'action' => '->checkAction' // you can only access this action if
     * $this->checkAction() returns true
     * );
     * </code>
     *
     * @var array
     */
    private static $allowed_actions = array(
    	'generate',
    	'download',
		'certificate'
	);

    public function init() {
        parent::init();
    }

    function generate(){
    	if($this->owner->CurrentMember()->exists() && ($trade_account = $this->owner->CurrentMember()->TradeAccounts()->byID($this->owner->request->param('ID'))) && $trade_account->TradeUnit > 0){
	        $img = imagecreatefrompng(sprintf('%s%s', Director::baseFolder(), Config::inst()->get('TradeSetting', 'certificate_template')));
	        $background_color = imagecolorallocate($img, 0, 0, 0);
	        $text_color = imagecolorallocate($img, 246, 226, 132);
			$text_font = i18n::get_locale() == 'zh_CN' ? sprintf('%s/trading/images/font/simhei.ttf', Director::baseFolder()) : sprintf('%s/trading/images/font/vijayab.ttf', Director::baseFolder());
			$name = strtoupper(sprintf('%s (%s)', $this->owner->CurrentMember()->Name, $this->owner->CurrentMember()->Username));
			$x = $this->center_text($name, 25, $text_font);
	        imagettftext($img, 25, 0, $x, 250, $text_color, $text_font, $name);
			$owned = _t('TradeCertificatePage.OWNED', 'OWNED');
			$x = $this->center_text($owned, 25, $text_font);
	        imagettftext($img, 25, 0, $x, 290, $text_color, $text_font, $owned);
			$title = _t(sprintf('%s.%s', 'TradeCertificatePage', strtoupper(str_replace(' ', '_', preg_replace("/[^ \w]+/", "", $trade_account->TradeSetting()->Title)))), strtoupper($trade_account->TradeSetting()->Title));
			$unit = _t('TradeCertificatePage.UNITS', '{unit} UNITS {title}', '', array('unit' => $trade_account->obj('TradeUnit')->Formatted(), 'title' => $title));
			$x = $this->center_text($unit, 25, $text_font);
	        imagettftext($img, 25, 0, $x, 330, $text_color, $text_font, $unit);
	        imagepng($img);
			imagedestroy($img);
			
	        $this->owner->response->addHeader("Content-Type", "image/png; charset=utf-8");
	        
	        return $this->owner->response;
		}

		return $this->owner->httpError('404');
    }

	function download(){
		if($this->owner->CurrentMember()->exists() && ($trade_account = $this->owner->CurrentMember()->TradeAccounts()->byID($this->owner->request->param('ID'))) && $trade_account->TradeUnit > 0){
	        $img = imagecreatefrompng(sprintf('%s%s', Director::baseFolder(), Config::inst()->get('TradeSetting', 'certificate_template')));
	        $background_color = imagecolorallocate($img, 0, 0, 0);
	        $text_color = imagecolorallocate($img, 246, 226, 132);
			$text_font = i18n::get_locale() == 'zh_CN' ? sprintf('%s/trading/images/font/simhei.ttf', Director::baseFolder()) : sprintf('%s/trading/images/font/vijayab.ttf', Director::baseFolder());
			$name = strtoupper(sprintf('%s (%s)', $this->owner->CurrentMember()->Name, $this->owner->CurrentMember()->Username));
			$x = $this->center_text($name, 25, $text_font);
	        imagettftext($img, 25, 0, $x, 250, $text_color, $text_font, $name);
			$owned = _t('TradeCertificatePage.OWNED', 'OWNED');
			$x = $this->center_text($owned, 25, $text_font);
	        imagettftext($img, 25, 0, $x, 290, $text_color, $text_font, $owned);
			$title = _t(sprintf('%s.%s', 'TradeCertificatePage', strtoupper(str_replace(' ', '_', preg_replace("/[^ \w]+/", "", $trade_account->TradeSetting()->Title)))), strtoupper($trade_account->TradeSetting()->Title));
			$unit = _t('TradeCertificatePage.UNITS', '{unit} UNITS {title}', '', array('unit' => $trade_account->obj('TradeUnit')->Formatted(), 'title' => $title));
			$x = $this->center_text($unit, 25, $text_font);
	        imagettftext($img, 25, 0, $x, 330, $text_color, $text_font, $unit);
			$file = sprintf('%s/trading/images/%s', Director::baseFolder(), sprintf('certificate_%s.png', time()));
	        imagepng($img, $file, 0);
			imagedestroy($img);
			$content = file_get_contents($file);
			unlink($file);
			return SS_HTTPRequest::send_file($content, sprintf('certificate_%s.png', time()), 'image/png');
		}

		return $this->owner->httpError('404');
	}
	
	protected function center_text($string, $font_size, $font_name){
        $image_width = 600;
        $dimensions = imagettfbbox($font_size, 0, $font_name, $string);
        return ceil(($image_width - $dimensions[4]) / 2);
	}

	function Certificates(){
		$list = ArrayList::create();
		foreach($this->owner->CurrentMember()->TradeAccounts() as $trade_account){
			if($trade_account->TradeUnit > 0){
				$trade_account->Link = Controller::join_links($this->owner->Link('generate'), $trade_account->ID);
				$trade_account->PrintLink = Controller::join_links($this->owner->Link('certificate'), $trade_account->ID);
				$trade_account->DownloadLink = Controller::join_links($this->owner->Link('download'), $trade_account->ID);
				$list->push($trade_account);
			}
		}
		
		return $list;
	}
	
	function certificate(){
		if($this->owner->CurrentMember()->exists() && ($trade_account = $this->owner->CurrentMember()->TradeAccounts()->byID($this->owner->request->param('ID'))) && $trade_account->TradeUnit > 0){
			return sprintf('<p align="center"><img src="%s" /></p>', Controller::join_links($this->owner->Link('generate'), $trade_account->ID));
		}
		
		return $this->owner->httpError('404');
	}
}
